import { dbconfig } from "../config/config";
import { createConnection, Connection,createPool, Pool  } from "mysql2";
import { log4js } from "../config/log4";
class _mysql{
    private static instance:_mysql
    /**异步连接 */
    public db:Pool;
    /**同步连接 */
    public pool;
    constructor(){
        this.db = createPool ({
            host:dbconfig.host,
            user:dbconfig.user,
            password:dbconfig.password,
            database:dbconfig.database
        })
        this.pool = this.db.promise()
        let sql:string = 'select * from cs'
        this.db.query(sql,(err,rows)=>{
            if(err){
                log4js.error("mysql连接池:启动失败",err)
            } else{
                //2小时执行一次sql
                this.heartbeat(7200000)
                this.db.on('connection',()=>{
                    console.log("mysql连接池:创建了一个新连接");
                })
                this.db.on('acquire',()=>{
                    console.log("mysql连接池:取出一条连接")
                })
                this.db.on('release',()=>{
                    console.log("mysql连接池:归还一条连接")
                })
                log4js.info("mysql连接池:启动成功")
            }
        })
        //select * from information_schema.SCHEMATA where SCHEMA_NAME = '需要查找的数据库名';
    }
    /**
     * 触发单例初始化函数,啥作用都没有,就是为了启动时触发db模块的单例
     */
    main(){}
    async 创建连接池(){
        return new Promise<Connection>(async (res, rej) => {
            let db:Connection = await createConnection ({
                host:dbconfig.host,
                user:dbconfig.user,
                password:dbconfig.password,
                database:dbconfig.database
            })
            res(db)
        })
    }
    /**
     * 获取单例
     */
    public static getInstance(){
        if(!this.instance){
            this.instance = new _mysql()
            return this.instance
        }else{
            return this.instance
        }
    }
    /**
     * mysql心跳,防止时间过长,连接池连接释放
     */
    private heartbeat(sj: number | undefined){
        setInterval(()=>{
            this.db.query('select * from cs', async (err, rows) => {})
        },sj)
        
    }
}
export let mysql:_mysql = _mysql.getInstance()